import os
from typing import Dict

class ResultExporter:
    def generate_filename(self, video_path: str) -> str:
        base = os.path.basename(video_path)
        name, _ = os.path.splitext(base)
        return f"{name}.txt"

    def _format_people(self, value):
        # 将出境人物的字典格式转为仅输出值为 True 的键名，使用、分隔
        if isinstance(value, dict):
            # 优先筛选布尔 True
            true_keys = [k for k, v in value.items() if isinstance(v, bool) and v]
            if true_keys:
                return "、".join(true_keys)
            # 次选处理字符串/数值：如果包含明确的 True/1/"True" 标记
            flag_keys = [k for k, v in value.items() if str(v).strip().lower() in ("true", "1", "是")]
            if flag_keys:
                return "、".join(flag_keys)
            # 再次兜底：如果是字符串映射（如 {'创业青年本人': '本人', ...}），优先取包含“本人”的键；否则取第一个键
            keys = list(value.keys())
            for k in keys:
                vv = value[k]
                if isinstance(vv, str) and ("本人" in vv or "创业" in k):
                    return k
            return keys[0] if keys else ""
        return value if value is not None else ""

    def save_to_txt(self, structured_data: Dict, output_path: str):
        lines = [
            f"视频时长: {structured_data.get('视频时长','')}",
            f"视频主题: {structured_data.get('视频主题','')}",
            f"出境人物: {self._format_people(structured_data.get('出境人物',''))}",
            f"视听符号: {structured_data.get('视听符号','')}",
            f"感情色彩: {structured_data.get('感情色彩','')}",
            f"语言风格: {structured_data.get('语言风格','')}",
            f"标题情感表达: {structured_data.get('标题情感表达','')}",
            f"标题平台话题: {structured_data.get('标题平台话题','')}",
            f"视频摘要: {structured_data.get('视频摘要','')}",
        ]
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write("\n".join(lines))


